package com.project.biz.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.biz.CmsRecoveryMemberBiz;
import com.project.biz.UserBiz;
import com.project.common.exception.ServiceException;
import com.project.entity.CmsRecoveryMember;
import com.project.mapper.CmsRecoveryMemberMapper;
import com.project.pojo.dto.RecoveryMemberDTO;
import com.project.pojo.model.ApplyRecoveryMemberModel;
import com.project.pojo.model.GetAllRecoveryMemberModel;
import com.project.pojo.model.RefuseApplyRecoveryMemberModel;
import com.project.pojo.model.StopRecoveryMemberModel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Description: 回收员业务层接口实现类
 * @Author: zhuchi
 * @CreateDate: 2020/11/9 13:13
 * @Version: 1.0
 */
@Service
public class CmsRecoveryMemberBizImpl extends ServiceImpl<CmsRecoveryMemberMapper, CmsRecoveryMember> implements CmsRecoveryMemberBiz {

    /**
     * 用户业务层接口类
     */
    @Autowired
    private UserBiz userBiz;

    /**
     * 查询回收员列表
     * @param getAllRecoveryMemberModel
     * @return
     */
    public IPage<RecoveryMemberDTO> getAllRecoveryMember(GetAllRecoveryMemberModel getAllRecoveryMemberModel){
        Page<RecoveryMemberDTO> page = new Page<>(getAllRecoveryMemberModel.getPageNo(), getAllRecoveryMemberModel.getPageSize());
        IPage<RecoveryMemberDTO> iPage = this.baseMapper.getAllRecoveryMember(page, getAllRecoveryMemberModel);
        return iPage;
    }

    /**
     * 查询回收员列表,返回集合
     * @param getAllRecoveryMemberModel
     * @return
     */
    public List<CmsRecoveryMember> getRecoveryMemberList(GetAllRecoveryMemberModel getAllRecoveryMemberModel){
        QueryWrapper<CmsRecoveryMember> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(getAllRecoveryMemberModel.getMobile())){
            queryWrapper.like("mobile", getAllRecoveryMemberModel.getMobile());
        }

        if (StringUtils.isNotBlank(getAllRecoveryMemberModel.getNickName())){
            queryWrapper.like("nick_name", getAllRecoveryMemberModel.getNickName());
        }

        if (StringUtils.isNotBlank(getAllRecoveryMemberModel.getRealName())){
            queryWrapper.like("real_name", getAllRecoveryMemberModel.getRealName());
        }

        if (StringUtils.isNotBlank(getAllRecoveryMemberModel.getIdCard())){
            queryWrapper.like("id_card", getAllRecoveryMemberModel.getIdCard());
        }

        if (null != getAllRecoveryMemberModel.getState() && getAllRecoveryMemberModel.getState() != 0){
            queryWrapper.eq("state", getAllRecoveryMemberModel.getState());
        }

        queryWrapper.eq("status", 1);
        queryWrapper.orderByDesc("recovery_member_id");
        List<CmsRecoveryMember> list = this.baseMapper.selectList(queryWrapper);
        return list;
    }

    /**
     * 申请回收员
     * @param applyRecoveryMemberModel
     * @param userId
     * @return
     */
    public int addApplyRecoveryMember(ApplyRecoveryMemberModel applyRecoveryMemberModel, Long userId){
        CmsRecoveryMember recoveryMember = new CmsRecoveryMember();

        int result = 0;
        //被驳回后重新填写信息提交
        if (null != applyRecoveryMemberModel.getRecoveryMemberId()){
            recoveryMember = this.baseMapper.selectById(applyRecoveryMemberModel.getRecoveryMemberId());
            if (recoveryMember.getState() == 1){
                throw new ServiceException("您的申请正在审核中,暂不能修改");
            }else if (recoveryMember.getState() == 2){
                throw new ServiceException("该申请已被同意");
            }

            BeanUtils.copyProperties(applyRecoveryMemberModel, recoveryMember);
            recoveryMember.setUpdateUser(userId);
            recoveryMember.setUpdateTime(new Date());
            recoveryMember.setState(1);//状态（1:待审核,2:通过,3:驳回,4:停用）

            result = this.baseMapper.updateById(recoveryMember);
        }else {//第一次申请
            CmsRecoveryMember checkRecoveryMember = this.getRecoveryMmberByUserId(userId);
            if (null != checkRecoveryMember){
                throw new ServiceException("您已申请过回收员,不能重复申请");
            }

            BeanUtils.copyProperties(applyRecoveryMemberModel, recoveryMember);
            recoveryMember.setCreateUser(userId);
            recoveryMember.setCreateTime(new Date());
            recoveryMember.setState(1);//状态（1:待审核,2:通过,3:驳回,4:停用）
            recoveryMember.setStatus(1);

            result = this.baseMapper.insert(recoveryMember);
        }

        return result;
    }

    /**
     * 同意回收员申请
     * @param recoveryMemberId
     * @param userId
     * @return
     */
    @Transactional(rollbackFor = Exception.class , isolation = Isolation.REPEATABLE_READ, timeout = 30)
    public int updateAgreeApplyRecoveryMember(Long recoveryMemberId, Long userId){
        int result = 0;
        //查询回收员申请信息
        CmsRecoveryMember recoveryMember = this.baseMapper.selectById(recoveryMemberId);
        if (null != recoveryMember){
            if (recoveryMember.getState() == 2){
                throw new ServiceException("该申请已被同意");
            }else if (recoveryMember.getState() == 3){
                throw new ServiceException("该申请已被拒绝");
            }

            recoveryMember.setState(2);//状态（1:待审核,2:通过,3:驳回,4:停用）
            recoveryMember.setUpdateUser(userId);
            recoveryMember.setUpdateTime(new Date());
            recoveryMember.setAgreeTime(new Date());
            result = this.baseMapper.updateById(recoveryMember);
            if (result > 0){
                //更新用户表用户类型字段,使申请用户为回收员类型
                this.userBiz.updateUserToRecoveryMmber(recoveryMember.getCreateUser());
            }
        }
        return result;
    }

    /**
     * 拒绝回收员申请
     * @param refuseApplyRecoveryMemberModel
     * @param userId
     * @return
     */
    @Transactional(rollbackFor = Exception.class , isolation = Isolation.REPEATABLE_READ, timeout = 30)
    public int updateRefuseApplyRecoveryMember(RefuseApplyRecoveryMemberModel refuseApplyRecoveryMemberModel, Long userId){
        int result = 0;
        //查询回收员申请信息
        CmsRecoveryMember recoveryMember = this.baseMapper.selectById(refuseApplyRecoveryMemberModel.getRecoveryMemberId());
        if (null != recoveryMember){
            if (recoveryMember.getState() == 2){
                throw new ServiceException("该申请已被同意");
            }else if (recoveryMember.getState() == 3){
                throw new ServiceException("该申请已被拒绝");
            }

            recoveryMember.setState(3);//状态（1:待审核,2:通过,3:驳回,4:停用）
            recoveryMember.setUpdateUser(userId);
            recoveryMember.setUpdateTime(new Date());
            recoveryMember.setRefuseTime(new Date());
            recoveryMember.setRefuseContent(refuseApplyRecoveryMemberModel.getRefuseContent());
            result = this.baseMapper.updateById(recoveryMember);
        }
        return result;
    }

    /**
     * 停用回收员
     * @param stopRecoveryMemberModel
     * @param userId
     * @return
     */
    @Transactional(rollbackFor = Exception.class , isolation = Isolation.REPEATABLE_READ, timeout = 30)
    public int updateStopRecoveryMember(StopRecoveryMemberModel stopRecoveryMemberModel, Long userId){
        int result = 0;
        //查询回收员申请信息
        CmsRecoveryMember recoveryMember = this.baseMapper.selectById(stopRecoveryMemberModel.getRecoveryMemberId());
        if (null != recoveryMember){
            if (stopRecoveryMemberModel.getType() == 1){//停用
                //状态（1:待审核,2:通过,3:驳回,4:停用）
                if (recoveryMember.getState() == 1){
                    throw new ServiceException("请先审核回收员信息");
                }else if(recoveryMember.getState() == 3){
                    throw new ServiceException("该回收员申请已被驳回,无需停用");
                }else if (recoveryMember.getState() == 4){
                    throw new ServiceException("该回收员已是停用状态");
                }

                recoveryMember.setState(4);//状态（1:待审核,2:通过,3:驳回,4:停用）

                //更新用户表用户类型字段,停用回收员
                this.userBiz.updateUserStopRecoveryMmber(recoveryMember.getCreateUser());
            }else {//启用
                //状态（1:待审核,2:通过,3:驳回,4:停用）
                if (recoveryMember.getState() == 1){
                    throw new ServiceException("请先审核回收员信息");
                }else if (recoveryMember.getState() == 2){
                    throw new ServiceException("所选回收员已是启用状态");
                }

                recoveryMember.setState(2);//状态（1:待审核,2:通过,3:驳回,4:停用）

                //更新用户表用户类型字段,使申请用户为回收员类型
                this.userBiz.updateUserToRecoveryMmber(recoveryMember.getCreateUser());
            }

            recoveryMember.setUpdateUser(userId);
            recoveryMember.setUpdateTime(new Date());
            result = this.baseMapper.updateById(recoveryMember);
        }
        return result;
    }

    /**
     * 根据用户ID获取回收员信息
     * @param userId
     * @return
     */
    public CmsRecoveryMember getRecoveryMmberByUserId(Long userId){
        QueryWrapper<CmsRecoveryMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("create_user", userId);
        return this.baseMapper.selectOne(queryWrapper);
    }

}
